package com.whpost.service.dao.cwqf;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.entity.cwqf.TCwqfKhzf;
import com.whpost.service.entity.cwqf.TbCrmCustomer;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author YinZhuoyi
 * @since 2025-08-26
 */
public interface TbCrmCustomerMapper extends BaseMapper<TbCrmCustomer> {


    @Select("select * from tb_crm_customer where party_code = #{code} and rownum=1")
    TbCrmCustomer selectByCode(@Param("code") String code);

    @Select("select * from (" +
            "    select " +
            "        t.*, " +
            "        ROW_NUMBER() OVER (PARTITION BY t.party_code ORDER BY t.id) as rn " +  // 按party_code分组，每组按主键排序取第一条
            "    from TB_CRM_CUSTOMER t " +
            "    where ${ew.sqlSegment} " +
            "        and t.post_xzjg_code like #{postXzjgCodeLike} || '%' " +
            "        and not exists (" +
            "            select 1 from t_cwqf_khjl_kh k " +  // 用select 1替代select *更高效
            "            where k.czy_code = #{czyCode} " +
            "              and k.party_code = t.party_code" +
            "        )" +
            ") temp " +
            "where temp.rn = 1")  // 只保留每组第一条记录
    IPage<TbCrmCustomer> selectCustomers(
            Page<TbCrmCustomer> page,
            @Param("postXzjgCodeLike") String postXzjgCodeLike,
            @Param("czyCode") String czyCode,
            @Param("ew") QueryWrapper wrapper
    );

}
